<template>
  <div class="padding flex direction-column height-100">
    <el-table
      v-loading="loading" class="table" :data="lists" height="100%"
      :header-cell-style="{
        color: 'white',
        backgroundColor: themeColor,
      }"
    >
      <el-table-column v-for="column in columns" :key="column.prop" v-bind="column">
        <template v-if="column.prop === 'discountFactor'" #default="{ row }">
          <input-number-editor
            v-if="row._editing" :value="row.discountFactor"
           @update="update(row, $event)"
          ></input-number-editor>
          <div v-else @click="row._editing = true" title="点击可修改">
            {{row.discountFactor}}
            <i class="el-icon-edit" style="color: gray;"></i>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { selectEnergyDiscountList, saveOrUpdate } from '@/api/energyDiscount'
import InputNumberEditor from '@/components/input-number-editor'

const api = {
  selectEnergyDiscountList,
  saveOrUpdate,
}
export default {
  name: 'energy-discount-coefficient',
  components: {
    InputNumberEditor
  },
  data () {
    return {
      loading: false,
      lists: [],
      columns: [
        { label: 'ID', prop: 'id' },
        { label: '能源名称', prop: 'name' },
        { label: '参考折标系数', prop: 'referenceCoefficient' },
        { label: '折标系数', prop: 'discountFactor' },
        { label: '折标系数单位', prop: 'discountFactorUnit' },
      ],
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
  },
  mounted () {
    this.query()
  },
  methods: {
    reload () {
      this.query()
    },
    query () {
      this.loading = true
      return api.selectEnergyDiscountList().then(res => {
        if (res.code === 200) {
          res.data.forEach(v => {
            v._editing = false
            v._value = v.discountFactor
          })
          this.lists = res.data
        }
      }).finally(() => {
        this.loading = false
      })
    },
    update (row, { value }) {
      // eslint-disable-next-line
      if (value != row._value) {
        row.discountFactor = value
        api.saveOrUpdate(row).then(res => {
          if (res.code === 200) {
            this.$message.success('更新成功')
            this.reload()
            row._editing = false
          }
        })
      } else {
        row._editing = false
      }
    },
    restore (row) {
      row.discountFactor = row._value
    },
    clear (row) {
      row.discountFactor = ''
    },
  },
}
</script>
